from collections import *
import re

def parse_class(line: str):
    name, lo1, hi1, lo2, hi2 = re.fullmatch(
        r'(.+): (\d+)-(\d+) or (\d+)-(\d+)', line
    ).groups()
    return (name, int(lo1), int(hi1), int(lo2), int(hi2))

def parse_ticket(line: str):
    return tuple(map(int, line.split(',')))

with open('input.txt') as file:
    classes = []
    my_ticket = None
    nearby_tickets = []

    parts = file.read().split('\n\n')

    for line in parts[0].splitlines():
        classes.append(parse_class(line))

    my_ticket = parse_ticket(parts[1].splitlines()[1])

    for line in parts[2].splitlines()[1:]:
        nearby_tickets.append(parse_ticket(line))
    
    result = 0

    for ticket in nearby_tickets:
        for field in ticket:
            for _, lo1, hi1, lo2, hi2 in classes:
                if lo1 <= field <= hi1 or lo2 <= field <= hi2:
                    break
            else:
                result += field

    print(result)            